<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤：
 * 步骤1：网页授权获取用户openid
 * 步骤2：使用统一支付接口，获取prepay_id
 * 步骤3：使用jsapi调起支付
*/

	include_once("./WxPayPubHelper/WxPayPubHelper.php");
	
    //获取订单总金额
	$total_fee=!empty($_GET['total_fee'])?$_GET['total_fee']*100:1;
	$item_name=!empty($_GET['item_name'])?$_GET['item_name']:'';
	$order_sn=!empty($_GET['order_sn'])?$_GET['order_sn']:'';
    $jsApiParameters=wxpay($total_fee,$item_name,$order_sn);
   function wxpay($total_fee,$item_name,$order_sn){

     //使用jsapi接口
	$jsApi = new JsApi_pub();
	//=========步骤1：网页授权获取用户openid============
	//通过code获得openid
	if (!isset($_GET['code']))
	{
		//触发微信返回code码
		$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
		 $state = json_encode(array(                
                "total_fee" => "$total_fee",
                "item_name" => "$item_name",
                "order_sn"=>"$order_sn"
            ));
        $url = str_replace("STATE", $state, $url);
		Header("Location: $url"); 
	}else
	{    
		//获取code码，以获取openid
	    $code = $_GET['code'];
		$jsApi->setCode($code);
		$openid = $jsApi->getOpenId();
		$temp=json_decode($_GET['state'],true);
        $fee= $temp['total_fee'];
        $body=$temp['item_name'];
	}
//=========步骤2：使用统一支付接口，获取prepay_id============
	//使用统一支付接口
	$unifiedOrder = new UnifiedOrder_pub();
	
	//设置统一支付接口参数
	//设置必填参数
	//appid已填,商户无需重复填写
	//mch_id已填,商户无需重复填写
	//noncestr已填,商户无需重复填写
	//spbill_create_ip已填,商户无需重复填写
	//sign已填,商户无需重复填写
	$unifiedOrder->setParameter("openid","$openid");//商品描述
	$unifiedOrder->setParameter("body","$body");//商品描述
	//自定义订单号，此处仅作举例
	$timeStamp = time();
	$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
	$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
	$unifiedOrder->setParameter("total_fee","$fee");//总金额
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址 
	$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
	//非必填参数，商户可根据实际情况选填
	//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	//$unifiedOrder->setParameter("attach","XXXX");//附加数据 
	//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
	//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
	//$unifiedOrder->setParameter("openid","XXXX");//用户标识
	//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

	$prepay_id = $unifiedOrder->getPrepayId();

	//=========步骤3：使用jsapi调起支付============
	$jsApi->setPrepayId($prepay_id);

	$jsApiParameters = $jsApi->getParameters();
	//echo $jsApiParameters;
	return $jsApiParameters;


}
	


	
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>微信安全支付</title>
<style>
*{ font-size:18px; margin:0; padding:0;}

.box{width:640px; margin:0 auto;}

button{background:#f86a14; color:#fff; width:400px; height:40px; border-radius: 10px 10px 10px 10px; margin:20px auto; display:block; }
.big{ width:600px; height:300px; background:#fafafa; border-radius: 10px 10px 10px 10px;}
.big a{ margin-left:20px; margin-top:20px;
 text-decoration:none; color:#000;line-height: 300px;text-align: center;font-size:38px;font-weight: bold;}
</style>
	<script type="text/javascript">
		//调用微信JS api 支付
		function jsApiCall()
		{
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest',
				<?php echo $jsApiParameters; ?>,
				function(res){
					WeixinJSBridge.log(res.err_msg);
                    var states = getUrlParam('state');
                    var  state= eval('('+states+')');
                    var order_sn=state['order_sn'];
            
					if(res.err_msg == "get_brand_wcpay_request:ok"){
                           //window.location.href='http://3ji.85598.com/index.php/Home/Order/wechatOrder?order_sn='+order_sn;
                           window.location.href="http://api.szl66.com/vshop.php/Home/Order/callbackWchatPay?order_sn="+order_sn;

					}else{
                          alert('系统繁忙,支付失败');
                         // window.location.href='http://3ji.85598.com/index.php/Home/Order/index';
                          window.location.href="http://api.szl66.com/vshop.php/Home/Order/index.html";
                         
					}
				}
			);
		}

		function callpay()
		{
			if (typeof WeixinJSBridge == "undefined"){
			    if( document.addEventListener )
			    {
			        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			    }
			    else if (document.attachEvent)
			    {
			        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
			        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			    }
			}else{
			    jsApiCall();
			}
		}
		//获取url中的参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        }
        window.onload=callpay();
	</script>
</head>
<body>
	<!-- </br></br></br></br>
	<div align="center" class="box">
	<div class="big"><a href="">最后一步加油！</a></div>
		<button style="width:410px; height:80px; line-height:80px;font-size:36px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;" type="button" onclick="callpay()" >立即支付</button>
	</div> -->
</body>
</html>